package im.composer.media.sound.misc;

import im.composer.audio.engine.Out;

import java.util.Deque;
import java.util.LinkedList;

import org.tritonus.share.sampled.FloatSampleBuffer;

public class PipedOut extends Out {

	protected Deque<FloatSampleBuffer> q = new LinkedList<>();
	private boolean dirty = true;
	
	public void put(FloatSampleBuffer e){
		check(e);
		q.offer(e);
	}

	private void check(FloatSampleBuffer e) throws IllegalArgumentException,IllegalStateException{
		if(getContext()==null){
			throw new IllegalStateException("not init yet!");
		}
		if(e==null){
			throw new IllegalArgumentException("may not be null!");
		}
		if(e.getSampleCount()!=bufferSize){
			throw new IllegalArgumentException("buffersize dismatch!");
		}
		if(e.getChannelCount()!=getContext().getOutputChannelCount()){
			throw new IllegalArgumentException("channel count dismatch!");
		}
		if(e.getSampleRate()!=getContext().getSampleRate()){
			throw new IllegalArgumentException("sample rate dismatch!");
		}
	}

	@Override
	protected void computeBuffer() {
		FloatSampleBuffer fsb = q.poll();
		if(fsb==null){
			if(dirty){
				buf.makeSilence();
				dirty = false;
			}
		}else{
			dirty = true;
			for(int i=0;i<buf.getChannelCount();i++){
				System.arraycopy(fsb.getChannel(i), 0, buf.getChannel(i), 0, bufferSize);
			}
		}
	}

}
